<?php

namespace app\controllers\supplier\uni\product;

use app\controllers\supplier\base\AdminController;
use app\models\product\Product as Model;
use app\controllers\admin\services\Product as Service;
use app\models\product\ProductAreaList;
use app\models\product\ProductImage;
use app\models\product\ProductProperty;
use app\models\product\ProductSku;
use app\models\product\ProductSkuName;
use app\models\product\ProductSkuValue;
use app\models\SetProductCommission;
use app\redis\Cache;
use app\redis\supplier\Check;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * Class ProductController
 * @package app\controllers\admin
 */
class ProductController extends AdminController
{
    public function actionList()
    {
        $title = $this->post('title');
        $id = $this->post('id');
        $status = $this->post('status');
        $export = $this->post('export');

        $page = intval($this->post('page', $this->page));
        $page_size = intval($this->post('pageSize', $this->pageSize));

        $sort = $this->post('sort');

        $brand_id = $this->post('brand_id');
        $category_id = $this->post('category_id');
        $area = $this->post('area');

        $query = Model::find()
            ->where(['!=', 'status', Model::$statusMapping['DELETE']])
            ->andWhere(['supplier_id' => $this->user->id])
            // ->with(['image']);
            ->with(['mainImage', 'image', 'image.image', 'category', 'area', 'area.name', 'brand']);
            // ->with(['mainImage', 'category', 'area', 'area.name', 'brand']);

        if ($status > Model::$statusMapping['ALL']) {
            $query->andWhere(['status' => $status]);
        }

        if ($sort) {
            $prop = substr($sort, 0, 1);
            $prop = $prop == '-' ? SORT_DESC : SORT_ASC;
            $order = substr($sort, 1);
            $query->orderBy([$order => $prop]);
            // var_dump([$order => $prop]);exit;
        } else {
            $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC]);
        }

        if ($brand_id) {
            $query->andWhere(['brand_id' => $brand_id]);
        }
        if ($category_id) {
            $query->andWhere(['category_id' => $category_id]);
        }
        if ($area) {
            $ids = ProductAreaList::find()
                ->where(['area_id' => $area])
                ->select(['product_id'])
                ->column();
            $query->andWhere(['id' => $ids]);
        }

        if ($id) {
            $query->andWhere(['id' => $id]);
        }
        if ($title) {
            $query->andWhere(['like', 'title', $title]);
        }

        // export
        if ($export) {
            return $this->success($query->asArray()->all());
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $page_size);

        $list = $query->offset(($page - 1) * $page_size)
            ->limit($page_size)
            ->asArray()
            ->all();

        return $this->success([
            $this->totalCount   => $totalCount,
            $this->totalPage    => $totalPage,
            $this->list         => $list,
        ]);

    }

    public function actionEdit()
    {
        $data = $this->post();
        $transaction = Yii::$app->db->beginTransaction();

        // 审核状态
        $data['status'] = 0;

        // var_dump($data['property']);exit;

        try {
            if (isset($data['id']) && $data['id'] > 0) {
                $model = Model::findOne(['id' => $data['id']]);
                if (!$model) {
                    return $this->fail('操作失败');
                }

                // area
                $area = ProductAreaList::find()
                    ->where(['product_id' => $model->id])
                    ->select(['area_id'])
                    ->column();
                $area_add = array_diff($data['area_id'], $area);
                $area_sub = array_diff($area, $data['area_id']);

                // image
                $image = ProductImage::find()
                    ->where(['product_id' => $model->id])
                    ->select(['image_id'])
                    ->column();
                $image_add = array_diff($data['image'], $image);
                $image_sub = array_diff($image, $data['image']);

                // property
                $ids = ArrayHelper::getColumn($data['property'], 'id');
                $property = ProductProperty::find()
                    ->where(['product_id' => $model->id])
                    ->select(['id'])
                    ->column();
                $property_add = array_diff($ids, $property);
                $property_sub = array_diff($property, $ids);
                $property_edit = array_diff($property, $property_sub);

                // sku
                $ids = ArrayHelper::getColumn($data['sku'], 'id');
                $sku = ProductSkuName::find()
                    ->where(['product_id' => $model->id])
                    ->select(['id'])
                    ->column();
                $sku_add = array_diff($ids, $sku);
                $sku_sub = array_diff($sku, $ids);
                $sku_edit = array_diff($sku, $sku_sub);

                // 佣金与差价
                $commissionDiff = SetProductCommission::findOne(['product_id' => $data['id']]);
                if ($commissionDiff) {
                    $x = ['SetProductCommission' => $data['commissionDiff']];
                    $commissionDiff->load($x);
                    $commissionDiff->save();
                }
                $commissionDiff_data = false;
            } else {
                $model = new Model();
                $model->supplier_id = $this->user->id;

                // 佣金与差价
                $commissionDiff_data = $data['commissionDiff'];

                //area
                $area_add = $data['area_id'];
                $area_sub = [];

                // image
                $image_add = $data['image'];
                $image_sub = [];

                // property
                $property_add = ArrayHelper::getColumn($data['property'], 'id');
                $property_sub = [];
                $property_edit = [];

                // sku
                $sku_add = ArrayHelper::getColumn($data['sku'], 'id');
                $sku_sub = [];
                $sku_edit = [];
            }

            // main image
            if ($data['image']) {
                $data['main_image'] = $data['image'][0];
            }

            $propertyList = $data['property'];
            $skuList = $data['sku'];
            $data = ['Product' => $data];
            if ($model->load($data) && $model->save()) {

                // 添加时佣金
                if ($commissionDiff_data) {
                    $commissionDiff = new SetProductCommission();
                    $x = ['SetProductCommission' => array_merge(['product_id' => $model->id], $commissionDiff_data)];
                    $commissionDiff->load($x);
                    $commissionDiff->save();
                }

                // area
                if ($area_sub) {
                    ProductAreaList::deleteAll(['area_id' => $area_sub, 'product_id' => $model->id]);
                }
                if ($area_add) {
                    foreach ($area_add as $item) {
                        $a = new ProductAreaList();
                        $a->product_id = $model->id;
                        $a->area_id = $item;
                        $a->save();
                    }
                }

                // image
                if ($image_sub) {
                    ProductImage::deleteAll(['image_id' => $image_sub, 'product_id' => $model->id]);
                }
                if ($image_add) {
                    foreach ($image_add as $item) {
                        $i = new ProductImage();
                        $i->product_id = $model->id;
                        $i->image_id = $item;
                        $i->save();
                    }
                }

                // property
                foreach ($propertyList as $item) {
                    // add
                    if (in_array($item['id'], $property_add)) {
                        if (!$item['name'] && !$item['value']) {
                            continue;
                        }
                        $p = new ProductProperty();
                        $p->product_id = $model->id;
                        $p->name = $item['name'];
                        $p->value = $item['value'];
                        $p->status = ProductProperty::$statusMapping['OK'];
                        $p->save();
                        continue;
                    }
                    // update
                    if (in_array($item['id'], $property_edit)) {
                        if (!$item['name'] && !$item['value']) {
                            continue;
                        }
                        $p = ProductProperty::findOne(['id' => $item['id']]);
                        $p->name = $item['name'];
                        $p->value = $item['value'];
                        $p->save();
                    }
                }

                // remove
                if ($property_sub) {
                    foreach ($property_sub as $item) {
                        $p = ProductProperty::findOne(['id' => $item]);
                        $p->status = ProductProperty::$statusMapping['DELETE'];
                        $p->save();
                    }
                }

                // sku
                foreach ($skuList as $item) {
                    // add
                    if (in_array($item['id'], $sku_add)) {
                        $s = new ProductSkuName();
                        $s->product_id = $model->id;
                        $s->name = $item['name'];
                        $s->status = ProductSkuName::$statusMapping['OK'];
                        $s->save();
                        foreach ($item['value'] as $v) {
                            if (!$v['v']) {
                                continue;
                            }
                            $sv = new ProductSkuValue();
                            $sv->product_sku_name_id = $s->id;
                            $sv->value = $v['v'];
                            $sv->status = ProductSkuValue::$statusMapping['OK'];
                            $sv->save();
                        }
                        continue;
                    }

                    // update
                    if (in_array($item['id'], $sku_edit)) {
                        $s = ProductSkuName::findOne(['id' => $item['id']]);
                        $s->name = $item['name'];
                        $s->save();

                        // var_dump($item['value']);exit;
                        if ($item['value']) {
                            foreach ($item['value'] as $v) {
                                if (isset($v['id']) && $v['id'] > 0) {
                                    // 空值代表删除
                                    $sv = ProductSkuValue::findOne(['id' => $v['id']]);
                                    if (!trim($v['v'])) {
                                        $sv->status = ProductSkuValue::$statusMapping['DELETE'];
                                    } else {
                                        $sv->value = $v['v'];
                                    }
                                    $sv->save();
                                } else {
                                    $sv = new ProductSkuValue();
                                    $sv->product_sku_name_id = $s->id;
                                    $sv->value = $v['v'];
                                    $sv->status = ProductSkuValue::$statusMapping['OK'];
                                    $sv->save();
                                }
                            }
                        }

                    }

                }

                // remove
                if ($sku_sub) {
                    foreach ($sku_sub as $item) {
                        $s = ProductSkuName::findOne(['id' => $item]);
                        $s->status = ProductSkuName::$statusMapping['DELETE'];
                        $s->save();
                    }
                }

            } else {
                throw new \Exception(json_encode($model->getErrors()));
            }

            // clear cache
            Cache::deleteAll(Cache::$PRODUCT_DETAIL);

            $transaction->commit();

            //check
            Check::produce('Product', $model->id, '商品');

            return $this->success($model);
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage(). $e->getLine());
        }
    }

    public function actionView()
    {
        $id = $this->post('id');
        $model = Model::find()
            ->where(['id' => $id])
            ->andWhere(['supplier_id' => $this->user->id])
            // ->with(['image', 'image.image', 'mainImage', 'area', 'area.name', 'properties', 'skuName', 'skuName.values'])
            ->with(['image', 'image.image', 'mainImage', 'area', 'area.name', 'properties', 'skuName', 'skuName.values', 'commissionDiff'])
            ->asArray()
            ->one();

        if ($model) {
            return $this->success($model);
        }

        return $this->fail('不存在该商品');
    }

    public function actionRemove()
    {
        $id = $this->post('id');

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = Model::$statusMapping['DELETE'];
            $model->save();
            return $this->success($model, '删除成功');
        } catch (\Exception $e) {
            return $this->fail($e->getMessage());
        }
    }

    public function actionStatusList()
    {
        return $this->success(Model::statusList());
    }

    public function actionChangeStatus()
    {
        $id = intval($this->post('id'));
        $status = intval($this->post('status'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->status = $status;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionChangeRecommend()
    {
        $id = intval($this->post('id'));
        $recommend = intval($this->post('recommend'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->is_recommend = $recommend;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionChangeSort()
    {
        $id = intval($this->post('id'));
        $sort = intval($this->post('sort'));

        try {
            $model = Model::findOne(['id' => $id]);
            $model->sort = $sort;
            $model->save();

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('操作错误: ' . $e->getMessage());
        }
    }

    public function actionBatchRemove()
    {
        $ids = $this->post('ids');

        try {
            Model::updateAll(['status' => Model::$statusMapping['DELETE']], ['id' => $ids]);

            return $this->success();
        } catch (\Exception $e) {
            return $this->fail('删除错误: ' . $e->getMessage());
        }
    }
}